<template>
  <el-dialog
    v-loading="loading"
    :visible.sync="dialog"
    :close-on-click-modal="false"
    title="Trait号变更"
    append-to-body
    width="95%"
    @close="cancel"
  >
    <div class="app-container">
      <el-button v-if="createFlag === false" class="filter-item" size="mini" type="primary" style="float:right;margin-bottom:5px;margin-left:0px;" round @click="doBatchUpdate">保存</el-button>
      <el-button v-if="createFlag === false" class="filter-item" size="mini" type="primary" style="float:right;margin-bottom:5px;margin-left:0px;" round @click="doBatchValidate">批量校验</el-button>
      <el-button v-if="createFlag === false" class="filter-item" size="mini" type="primary" style="float:right;margin-bottom:5px;margin-left:0px;" round @click="doSubmitBPMS">提交审核</el-button>
      <el-button v-if="createFlag === true" class="filter-item" size="mini" type="primary" style="float:right;margin-bottom:5px;margin-left:0px;" round @click="downloadExcelTemplate(parent.$route.name, 1)">下载导入模板</el-button>
      <el-button v-if="createFlag === true" class="filter-item" size="mini" type="primary" style="float:right;margin-bottom:5px;margin-left:0px;" round @click="exportTempDataExcel(data, parent.$route.name)">导出</el-button>
      <el-button v-if="createFlag === true" class="filter-item" size="mini" type="primary" style="float:right;margin-bottom:5px;margin-left:0px;" round @click="doBatchCreate">保存</el-button>
      <el-button class="filter-item" size="mini" type="primary" style="float:right;margin-bottom:5px;margin-left:0px;" round @click="doReadInfo">获取Item信息</el-button>
      <div v-if="createFlag === true" style="margin-bottom:5px;">
        <el-form :inline="true" size="small" label-width="auto">
          <el-form-item label="商品号：">
            <el-input v-model="itemNbrTxt" placeholder="输入商品号以行分隔" rows="5" type="textarea" style="width: 280px;" />
          </el-form-item>
          <el-form-item label="采购ID：">
            <el-select v-model="buyerId" style="width: 280px;">
              <el-option v-for="bid in buyerList" :key="bid" :label="bid" :value="bid" />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <el-table :data="data" stripe size="small" border :height="tableHeight" style="width: 100%;" @header-dragend="colChange">
        <el-table-column type="index" align="center" fixed width="55" label="序号" />
        <el-table-column v-if="createFlag === true" label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click.native.prevent="deleteRow(scope.$index)">移除该项</el-button>
          </template>
        </el-table-column>
        <el-table-column v-if="createFlag === false" label="校验信息">
          <template slot-scope="scope">
            <!--<el-popover
              v-if="scope.row.errorMsg && JSON.parse(scope.row.errorMsg).length > 0"
              placement="bottom"
              title="校验信息"
              trigger="click"
            >
              <div style="height:400px;overflow:auto;">
                <div v-for="(msg,index) in JSON.parse(scope.row.errorMsg)" :key="index" :index="index">
                  <span>{{ (index + 1) + '.' + msg }}</span>
                </div>
              </div>
              <el-button slot="reference" size="mini" type="text" style="color:#fc1111">点击查看</el-button>
            </el-popover>-->
            <validateMsg :item="scope.row" :type="3" />
          </template>
        </el-table-column>
        <el-table-column label="商品号" prop="itemNbr" :width="colWidths.itemNbr" />
        <el-table-column label="商品名称" prop="item1Desc" :width="colWidths.item1Desc" />
        <el-table-column label="现系统发送特号" prop="itemSendTrait" :width="colWidths.itemSendTrait" />
        <el-table-column label="现系统不发送特号" prop="itemOmitSendTrait" :width="colWidths.itemOmitSendTrait" />
        <el-table-column label="新发送特号" prop="newSendTrait" :width="colWidths.newSendTrait">
          <template slot-scope="scope">
            <el-input v-model="scope.row.newSendTrait" class="filter-item" :width="colWidths.newSendTrait" />
          </template>
        </el-table-column>
        <el-table-column label="新不发送特号" prop="newOmitSendTrait" :width="colWidths.newOmitSendTrait">
          <template slot-scope="scope">
            <el-input v-model="scope.row.newOmitSendTrait" class="filter-item" :width="colWidths.newOmitSendTrait" />
          </template>
        </el-table-column>
        <el-table-column label="未来生效日期" prop="futureEffDate" :width="colWidths.futureEffDate">
          <template slot-scope="scope">
            <el-input v-model="scope.row.futureEffDate" class="filter-item" :width="colWidths.futureEffDate" />
          </template>
        </el-table-column>
        <el-table-column label="加送或减送" prop="addOrOmit" :width="colWidths.addOrOmit" />
        <el-table-column label="增送店订单号或库存" prop="addStorePOOrOH" :width="colWidths.addStorePOOrOH">
          <template slot-scope="scope">
            <el-input v-model="scope.row.addStorePOOrOH" class="filter-item" :width="colWidths.addStorePOOrOH" />
          </template>
        </el-table-column>
        <el-table-column label="如何处理库存" prop="omitStoreRTV" :width="colWidths.omitStoreRTV">
          <template slot-scope="scope">
            <el-input v-model="scope.row.omitStoreRTV" class="filter-item" :width="colWidths.omitStoreRTV" />
          </template>
        </el-table-column>
        <el-table-column label="新建交叉链" prop="newRef" :width="colWidths.newRef">
          <template slot-scope="scope">
            <el-input v-model="scope.row.newRef" class="filter-item" :width="colWidths.newRef" />
          </template>
        </el-table-column>
        <el-table-column label="是否为主商品" prop="icon" :width="colWidths.icon">
          <template slot-scope="scope">
            <el-input v-model="scope.row.icon" class="filter-item" :width="colWidths.icon" />
          </template>
        </el-table-column>
        <el-table-column label="地区价格" prop="obPrice" :width="colWidths.obPrice">
          <template slot-scope="scope">
            <el-input v-model="scope.row.obPrice" class="filter-item" :width="colWidths.obPrice" />
          </template>
        </el-table-column>
        <el-table-column label="是否删除次商品" prop="oldItemDelete" :width="colWidths.oldItemDelete">
          <template slot-scope="scope">
            <el-input v-model="scope.row.oldItemDelete" class="filter-item" :width="colWidths.oldItemDelete" />
          </template>
        </el-table-column>
        <el-table-column label="英文说明" prop="item2Desc" :width="colWidths.item2Desc" />
        <el-table-column label="商品状态" prop="itemStatusCode" :width="colWidths.itemStatusCode" />
        <el-table-column label="商品类型" prop="itemTypeCode" :width="colWidths.itemTypeCode" />
        <el-table-column label="次类型" prop="replSubtypeCode" :width="colWidths.replSubtypeCode" />
        <el-table-column label="部门号" prop="deptNbr" :width="colWidths.deptNbr" />
        <el-table-column label="供应商编号" prop="vendorNbr" :width="colWidths.vendorNbr" />
        <el-table-column label="供应商名称" prop="vendorName" :width="colWidths.vendorName" />
        <el-table-column label="条形码" prop="upcNbr" :width="colWidths.upcNbr" />
        <el-table-column label="供应商之商品代码" prop="vendorStockId" :width="colWidths.vendorStockId" />
        <el-table-column label="现区域码" prop="buyingRegionCode" :width="colWidths.buyingRegionCode" />
        <el-table-column label="箱包装数量" prop="vnpkQty" :width="colWidths.vnpkQty" />
        <el-table-column label="仓包数量" prop="whpkQty" :width="colWidths.whpkQty" />
        <el-table-column label="细分类" prop="finelineNbr" :width="colWidths.finelineNbr" />
        <el-table-column label="交叉链中商品" prop="itemCross" :width="colWidths.itemCross" />
        <el-table-column label="转运代码" prop="whseAlignTypeCd" :width="colWidths.whseAlignTypeCd" />
        <el-table-column label="折扣券更改备注" prop="couponChangeRemark" :width="colWidths.couponChangeRemark">
          <template slot-scope="scope">
            <el-input v-model="scope.row.couponChangeRemark" class="filter-item" :width="colWidths.couponChangeRemark" />
          </template>
        </el-table-column>
        <el-table-column label="鲜食备注" prop="pfsRemark" :width="colWidths.pfsRemark">
          <template slot-scope="scope">
            <el-input v-model="scope.row.pfsRemark" class="filter-item" :width="colWidths.pfsRemark" />
          </template>
        </el-table-column>
        <el-table-column label="Store Nbr" prop="traitMaitenceFormTraitNbr" :width="colWidths.traitMaitenceFormTraitNbr" />
      </el-table>
    </div>
    <urgentForm ref="urgentForm" :parent="parent" />
  </el-dialog>
</template>

<script>
import { Message } from 'element-ui'
import { parseTime } from '@/utils/index'
import { batchUpdateItem, batchCreateTraitItem, queryTraitItemInfo, batchValidate, queryList } from '@/api/change-item'
import urgentForm from './urgent'
import { exportTempDataExcel, downloadExcelTemplate } from '@/utils/item'
import initTable from '@/utils/initTable'
import validateMsg from '@/views/part/validateMsg'

export default {
  components: { urgentForm, validateMsg },
  mixins: [initTable],
  props: {
    parent: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      dialog: false,
      data: [],
      loading: false,
      tableHeight: window.innerHeight * 0.7,
      createFlag: false,
      itemNbrTxt: '',
      buyerList: [],
      buyerId: ''
    }
  },
  methods: {
    exportTempDataExcel,
    downloadExcelTemplate,
    cancel() {
      this.data = []
      this.itemNbrTxt = ''
      this.buyerList = []
      this.buyerId = ''
    },
    // 修改保存触发
    doBatchUpdate() {
      this.$confirm('是否变更该 ' + this.data.length + ' 条item信息?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        const val = []
        this.data.forEach(item => {
          item.changeTime = parseTime(new Date())
          val.push({ id: item.id, itemInfo: JSON.stringify(item) })
        })
        batchUpdateItem(val).then(() => {
          Message({
            message: '变更成功。',
            type: 'success',
            duration: 3 * 1000
          })
          this.parent.toQuery()
          this.loading = false
        }, (error) => {
          console.log(error)
          this.loading = false
        })
      })
    },
    // 删除一行
    deleteRow(index) {
      this.data.splice(index, 1)
    },
    // 新增保存触发
    doBatchCreate() {
      if (this.data.length < 1) {
        Message({
          message: '请编辑需要新增的Item。',
          type: 'error',
          duration: 3 * 1000
        })
      } else {
        this.$confirm('是否新增该 ' + this.data.length + ' 条item信息?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading = true
          const val = []
          this.data.forEach(item => {
            item.changeTime = parseTime(new Date())
            val.push({ id: '', buyerId: this.buyerId, itemInfo: JSON.stringify(item) })
          })
          batchCreateTraitItem(val).then(() => {
            Message({
              message: '新增成功。',
              type: 'success',
              duration: 3 * 1000
            })
            this.parent.toQuery()
            this.loading = false
            this.dialog = false
          }, (error) => {
            console.log(error)
            this.loading = false
          })
        })
      }
    },
    // 读取数据
    doReadInfo() {
      if (this.createFlag === true && (!this.itemNbrTxt || this.itemNbrTxt === '')) {
        Message({
          message: '请编辑需要新增的Item。',
          type: 'error',
          duration: 3 * 1000
        })
      } else if (this.itemNbrTxt.length > 1000) {
        Message({
          message: '所需获取的信息过多，请使用Excel导入方式进行操作。',
          type: 'error',
          duration: 3 * 1000
        })
      } else {
        this.loading = true
        let _itemNbrTxt = this.itemNbrTxt.trim() // 去掉两头空格
        _itemNbrTxt = _itemNbrTxt.replace(/[\n\r\s]/g, '-')
        const itemArray = _itemNbrTxt.split('-')
        const sourceData = []
        for (let i = 0; i < this.data.length; i++) {
          sourceData.push(this.data[i])
        }
        itemArray.forEach(_itemNbr => {
          if (_itemNbr && _itemNbr !== '') {
            this.data.push({ itemNbr: _itemNbr })
          }
        })
        const indexRemoveDate = []
        const itemNbrs = []
        this.data.forEach(item => {
          itemNbrs.push(item.itemNbr)
        })
        queryTraitItemInfo(itemNbrs).then(res => {
          if (res) {
            if (res.itemInfoList) {
              res.itemInfoList.forEach(dbItem => {
                for (let i = 0; i < this.data.length; i++) {
                  if (this.data[i].itemNbr.toString() === dbItem.itemNbr.toString()) {
                    if (res.traitList) { // 发送区域
                      const s_trait = []
                      const o_trait = []
                      res.traitList.forEach(trait => {
                        if (this.data[i].itemNbr.toString() === trait.itemNbr.toString()) {
                          if (trait.traitGroupType === 'S') {
                            s_trait.push(trait.traitNbr)
                          } else if (trait.traitGroupType === 'O') {
                            o_trait.push(trait.traitNbr)
                          }
                        }
                      })
                      dbItem.itemSendTrait = s_trait.join('O')
                      dbItem.itemOmitSendTrait = o_trait.join('O')
                    }
                    if (res.refList) { // 次商品交叉关联
                      const refs = []
                      res.refList.forEach(ref => {
                        if (this.data[i].itemNbr.toString() === ref.itemNbr.toString()) {
                          refs.push(ref.refItemNbr)
                        }
                      })
                      dbItem.itemCross = refs.join(';')
                    }
                    const _data = this.data[i]
                    dbItem.id = _data.id
                    dbItem.newSendTrait = _data.newSendTrait ? _data.newSendTrait : dbItem.newSendTrait
                    dbItem.newOmitSendTrait = _data.newOmitSendTrait ? _data.newOmitSendTrait : dbItem.newOmitSendTrait
                    dbItem.futureEffDate = _data.futureEffDate ? _data.futureEffDate : dbItem.futureEffDate
                    dbItem.addStorePOOrOH = _data.addStorePOOrOH ? _data.addStorePOOrOH : dbItem.addStorePOOrOH
                    dbItem.omitStoreRTV = _data.omitStoreRTV ? _data.omitStoreRTV : dbItem.omitStoreRTV
                    dbItem.newRef = _data.newRef ? _data.newRef : dbItem.newRef
                    dbItem.icon = _data.icon ? _data.icon : dbItem.icon
                    dbItem.obPrice = _data.obPrice ? _data.obPrice : dbItem.obPrice
                    dbItem.oldItemDelete = _data.oldItemDelete ? _data.oldItemDelete : dbItem.oldItemDelete
                    this.data.splice(i, 1, dbItem)
                    indexRemoveDate.push(i)
                  }
                }
              })
              let deletFalge = 0
              var errorItem = ''
              for (let i = 0; i < this.data.length; i++) {
                if (indexRemoveDate.indexOf(i + deletFalge) === -1) {
                  errorItem = errorItem + this.data[i].itemNbr.toString() + ','
                  this.data.splice(i, 1)
                  i -= 1
                  deletFalge += 1
                }
              }
              if (errorItem && errorItem.length > 0) {
                Message({
                  message: '无效商品号：' + errorItem.substring(0, errorItem.length - 1),
                  type: 'warning',
                  duration: 3 * 1000
                })
              }
            }
          }
          this.loading = false
        }, (error) => {
          console.log(error)
          this.data = sourceData
          this.loading = false
        })
      }
    },
    // 批量提交审核前置
    doSubmitBPMS() {
      if (this.data.length < 1) {
        Message({
          message: '请选择需要提交审核的item。',
          type: 'error',
          duration: 3 * 1000
        })
      } else {
        const _this = this.$refs.urgentForm
        _this.itemSize = this.data.length
        _this.changeType = this.parent.$route.name
        const ids = []
        this.data.forEach(item => {
          ids.push(item.id)
        })
        _this.bpmsParam.auditBuyerId = this.parent.auditBuyerId
        _this.ids = ids
        _this.dialog = true
      }
    },
    // 批量校验
    doBatchValidate() {
      this.$confirm('确认校验该 ' + this.data.length + ' 条item信息?', '校验数据', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        const ids = []
        this.data.forEach(item => {
          ids.push(item.id)
        })
        batchValidate({ ids: ids, changeType: this.parent.$route.name }).then(res => {
          queryList({ ids: ids, changeType: this.parent.$route.name }).then(dataList => {
            if (dataList) {
              const _data = []
              dataList.forEach(dataObj => {
                _data.push(JSON.parse(dataObj.itemInfo))
              })
              this.data = _data
            }
          })
          this.parent.toQuery()
          Message({
            message: '校验处理中，请稍后刷新页面进行查询。',
            type: 'success',
            duration: 3 * 1000
          })
          this.loading = false
        }, error => {
          console.log(error)
          this.loading = false
        })
      })
    }
  }
}
</script>

